package Z11_12_customizedPool;

import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： pang-yun
 * @date： 2021-11-20 11:09
 * 功能目的 ：用于 测试线程池 中 submit  返回 future
 */
@Slf4j
public class PoolSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //  创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private AtomicInteger atomicInteger = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "Pang-" + atomicInteger.getAndIncrement());
            }
        });

        invokeAny(pool);
    }
    // 提交 task 所有任务  那个任务先完成则返回结果 其他任务取消
    private static void invokeAny(ExecutorService pool) throws InterruptedException, ExecutionException {
        Object future = pool.invokeAny(Arrays.asList(() -> {
                    TimeUnit.SECONDS.sleep(1);
                    return "A";
                },
                () -> {
                    TimeUnit.SECONDS.sleep(1);
                    return "B";
                }));

        System.out.println(future);
    }

    private static void invokeAll(ExecutorService pool) throws InterruptedException {
        // 提交所有任务  是  callable 的一个集合
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(() -> {
                    TimeUnit.SECONDS.sleep(1);
                    return "A";
                },
                () -> {
                    TimeUnit.SECONDS.sleep(1);
                    return "B";
                })
        );

        futures.stream().forEach(a-> {
            try {
                log.info("{}",a.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }


    //  callable 接口 提交任务  还有 返回结果
    private static void submit(ExecutorService pool) throws InterruptedException, ExecutionException {
        Future<String> submit = pool.submit(() -> {
            TimeUnit.SECONDS.sleep(1);
            return "ok";
        });

        log.info("{}", submit.get());
    }
}
